package com.qust.enDecrpytion.proxy.status;

import com.qust.enDecrpytion.cache.DecryptionLru;
import com.qust.enDecrpytion.cache.EncryptionLru;
import com.qust.enDecrpytion.proxy.IStatusOfType;
import com.qust.enDecrpytion.proxy.StatusHandleFunction;
import lombok.Getter;
import lombok.Setter;

import java.lang.annotation.Annotation;
import java.util.ArrayList;

public class TypeHandleContext implements IStatusOfType{
    @Setter
    @Getter
    private DecryptionLru decryptionLru;
    @Setter
    @Getter
    private EncryptionLru encryptionLru;

    private ArrayList<AbstractTypeHandle> handles = new ArrayList<>();

    public TypeHandleContext() {

    }

    public TypeHandleContext addHandle(AbstractTypeHandle handle){
        handle.setEncryptionLru(encryptionLru);
        handle.setDecryptionLru(decryptionLru);
        handles.add(handle);
        return this;
    }

    @Override
    public <T> T handle(T target,boolean cache ,Class<? extends Annotation> annotation, StatusHandleFunction function) {
        try {
            T result;
            for (AbstractTypeHandle handle : handles) {
                result = handle.handle(target,cache,annotation,function);
                if (result != null){
                    return result;
                }
            }
            throw new RuntimeException("没有该类型handler");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
